<!--
 * @Author: zhangjingyu
 * @Date: 2020-10-22 19:30:00
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-04-27 10:44:20
 * @FilePath: \vprisk10.14\src\views\SystemMange\orgManage.vue
 * @Description: 机构管理
-->

<template>
  <!-- 机构管理页面 -->
  <div>
    <el-row class="caliberHierarchy container" :gutter="10">
      <!-- 左侧树 -->
       <el-col :span="6"  style="padding-top:10px;padding:0 10px" >
        <vp-tree
        :vp-header="{show:true,text:'机构组织',search:true,name:'orgName'}"
        vp-title="所有机构"
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          check-strictly
          ref="configTree"
          node-key="orgId"
          :expand-on-click-node="false"
          check-on-click-node
          :render-content="rendertree"
        ></vp-tree>
      </el-col>
      <!-- 右侧表  -->
      <el-col  :span="18" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <el-button  @click="addFunc">新增</el-button>
            <el-button  @click="editFunc">编辑</el-button>
            <el-button  @click="startOrBackFunc(1)"
              >启用</el-button
            >
            <el-button  @click="startOrBackFunc(0)"
              >停用</el-button
            >
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
                <!-- <i class="iconfont icon-export" title="导出"></i> -->
              <!-- <i class="iconfont icon-import" title="导入"></i> -->
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="87px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="机构代码：">
                      <el-input
                        v-model="searchForm.orgCode"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="机构名称：">
                      <el-input
                        v-model="searchForm.orgName"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="机构状态：">
                      <el-select
                        v-model="searchForm.status"
                        clearable 
                      >
                        <el-option value="1" label="启用"></el-option>
                        <el-option value="0" label="停用"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>

                  <div style="text-align:center;padding:10px">
                    <el-button  size="mini" @click="searchForm.page=1,searchFunc()"
                      >查询</el-button
                    >
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.orgCode = ''),
                          (searchForm.orgName = ''),
                          (searchForm.status = '')
                      "
                      >重置</el-button
                    >
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="orgCode"
            label="机构代码"
            v-if="columnState[0]"
          >
          </el-table-column>
          <el-table-column
            prop="orgName"
            label="机构名称"
            sortable
            :show-overflow-tooltip="true"
            v-if="columnState[1]"
          >
          </el-table-column>
          <el-table-column
            prop="orgParentName"
            :show-overflow-tooltip="true"
            label="上级机构"
            sortable
            v-if="columnState[2]"
          >
          </el-table-column>

          <el-table-column
            prop="status"
            label="机构状态"
            v-if="columnState[3]"
            :filter-method="(val, row) => row.status === val"
            :filters="[
              { text: '启用', value: '1' },
              { text: '停用', value: '0' }
            ]"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == 1">
                <i class="startState"></i><span>启用</span>
              </div>
              <div v-if="scope.row.status == 0">
                <i class="unStartState"></i><span style="color:red">停用 </span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @refresh="searchFunc"
          :current-page="searchForm.page"
        :page-size="searchForm.size"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        :label-width="'97px'"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构代码：" prop="orgCode">
              <el-input
                v-model="saveForm.orgCode"
                maxlength="40"
                        :disabled="saveFlg==2"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机构名称：" prop="orgName">
              <el-input
                v-model="saveForm.orgName"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机构层级：" prop="orgLevel" >
              <el-select
                v-model="saveForm.orgLevel"
                placeholder=""
                disabled
                        clearable 
                        style="width:100%"
              >
                <el-option
                  v-for="item in orgLevelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="上级机构：" prop="parentOrgId">
              <el-tooltip
                :content="saveOrgTip"
                :disabled="!saveOrgTip"
                placement="top"
                class="item"
              >
                <el-cascader
                  clearable
                  filterable
                  :options="orgList"
                  v-model="saveForm.parentOrgId"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    expendTrigger: 'hover',
                    value: 'orgId',
                    label: 'orgName'
                  }"
                  :show-all-levels="false"
                  ref="saveOrgTree"
                  style="width:100%"
                  @change="checkFormOrg"
                ></el-cascader>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系人：" prop="linkman">
              <el-input
                v-model="saveForm.linkman"
                maxlength="24"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系电话：" prop="linktel">
              <el-input
                v-model="saveForm.linktel"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机构网址：" prop="weburl">
              <el-input
                v-model="saveForm.weburl"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机构邮箱：" prop="email">
              <el-input
                v-model="saveForm.email"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮政编码：" prop="zipCode">
              <el-input
                v-model="saveForm.zipCode"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="机构地址：" prop="orgAddr">
              <el-input
                v-model="saveForm.orgAddr"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="机构状态：" prop="status">
              {{saveForm.status === '1'?'启用':'停用'}}
            </el-form-item>
          </el-col>
          <el-col  :span="13">
            <el-form-item label="机构内部层级："  prop="orgDegree" :label-width="'120px'">
              <el-select
                v-model="saveForm.orgDegree"
                placeholder="请选择"
                        clearable 
                        :title="$getLabel(saveForm.orgDegree,orgDegreelList)"
              >
                <el-option
                  v-for="item in orgDegreelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :title="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="是否部门：" prop="orgDeptFlag">
              <el-radio-group v-model="saveForm.orgDeptFlag" @change="orgDeptFlagChange">
                <el-radio v-for="item in orgDeptFlagList" :label="item.value"   :key="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="部门类型：" prop="orgType">
              <el-select
                v-model="saveForm.orgType"
                placeholder="请选择"
                @change="$refs.saveForm.validateField('orgType')"
                        clearable 
                :disabled="saveForm.orgDeptFlag!=1"
              >
                <el-option
                  v-for="item in orgTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import { listToTree } from "@/lib/util"; // list转tree
import { getDict } from "@/api/getDict"; // 字典接口

export default {
  data() {
    return {
      filterText: "", // 节点过滤关键字
      userName: "", //右侧用户名
      userDo: "授权角色", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["新增机构", "编辑机构"],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }]
        }
      ],
      clickNode: {},
      // 左侧机构树data
      treeData: [],
      defaultProps: {
        children: "children",
        label: "orgName"
      },
      // 角色管理下拉框
      mgrRoleIdList: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        }
      ],
      // search机构树悬停提示
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        orgName: "",
        ogrCode: "",
        status: "",
        page: 1,
        size: 15
      },
      total: 0,
      saveForm: {
        
orgCode:"",
orgName:"",
orgLevel:"",
parentOrgId:"",
linkman:"",
weburl:"",
email:"",
zipCode:"",
orgAddr:"",
status:"",
orgDegree:"",
orgDeptFlag:"",
orgType:"",
      },
      saveFormRules: {
        orgCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { pattern:/^[0-9a-zA-Z_]{3,32}$/,message:"只能输入3-32位的英文字母、数字、下划线",trigger: "blur"},
        ],
        orgName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { pattern:/^[\u4E00-\u9FA5A-Za-z0-9_]+$/,message:"只能输入英文字母、中文、数字和下划线",trigger: "blur"},

        ],
        linkman:[
          { pattern:/^[\u4E00-\u9FA5A-Za-z0-9_]+$/,message:"只能输入英文字母、中文、数字和下划线",trigger: "blur"},
        ],
        parentOrgId: [
          { required: true, message: "该输入项为必选项", trigger: "blur" },
          { validator: this.checkParentId, trigger: "blur" },
        ],
        // 电话
        linktel: [
          {pattern:/^0\d{2,3}-[1-9]\d{6,7}$/,message:"请按正确格式输入电话号码（区号-电话号码）",trigger: "blur"}
        ],
        weburl: [
          { type: "url", message: "请输入正确网址地址格式", trigger: "blur" }
          // { validator: this.validPassword, trigger: "blur" }
        ],
        email: [{ type: "email", message: "请输入正确邮箱格式", trigger: "blur" }],
        zipCode: [
          {
            pattern: /^[0-9]\d{5}(?!\d)$/,
            message: "请输入正确邮编格式",
            trigger: "blur"
          }
        ],
        orgType:[
          { validator: this.orgTypeValid, trigger: "blur" },
        ],
        // status: [
        //   { required: true, message: "该输入项为必输项", trigger: "blur" }
        // ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "roleCode", label: "机构代码" },
        { prop: "roleName", label: "机构名称" },
        { prop: "roleDesc", label: "上级机构 " },
        { prop: "mgrRole", label: "机构状态" }
      ],
      // 获取table的数据
      tableData: [],
      // 状态下拉框
      flgList: [],
      // 机构层级下拉
      orgLevelList: [],
      // 机构内部层级下拉框
      orgDegreelList: [],
      // 是否部门
      orgDeptFlagList: [],
      // 部门类型
      orgTypeList: [],
      oldParentOrgId: ""
    };
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  created() {
    this.checkListInit();
    this.getMgrOrganTree();
    this.getOrganTree();
    this.getDicts();
  },
  mounted() {},
  watch: {
      addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    orgTypeValid(rule,value,callback){
      if(this.saveForm.orgDeptFlag=='1'&&this.saveForm.orgType==''){
        callback(new Error('请选择部门类型'))
      }else{
        callback()
      }
    },
    // 获取所有字典下拉框
    // 获取字典
    getDicts() {
      // 启用锁定字典
      getDict("sys_userFlg").then(res => {
        if (res.code == 200) {
          this.flgList = res.datas;
        }
      });
      // 机构层级
      getDict("sys_org_orgLevel").then(res => {
        if (res.code == 200) {
          this.orgLevelList = res.datas;
        }
      });
      // 机构内部层级
      getDict("sys_orgDegree").then(res => {
        if (res.code == 200) {
          this.orgDegreelList = res.datas;
        }
      });
      // 是否部门
      getDict("sys_orgDeptFlag").then(res => {
        if (res.code == 200) {
          this.orgDeptFlagList = res.datas;
        }
      });
      // 部门类型
      getDict("sys_orgType").then(res => {
        if (res.code == 200) {
          this.orgTypeList = res.datas;
        }
      });
    },
    // filterTree() {
    //   this.$refs.configTree.$tree.filter(this.filterText);
    // },
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.orgName.indexOf(value) !== -1;
    // },
    // 获取机构选择树
    getOrganTree() {
      systemManage.getOrganTree().then(res => {
        this.orgList = res;
      });
    },
    // 获取左侧机构shu
    getMgrOrganTree() {
      systemManage.organManageTree().then(res => {
        if (res && res.code == 200) {
          this.treeData = listToTree("orgId", "parentId", res.datas);
          this.$nextTick(() => {
            this.handleNodeClick(this.treeData[0]);
          });
        }
      });
    },
    // 处理save表单机构选中事件
    checkFormOrg() {
      let node = this.$refs.saveOrgTree.getCheckedNodes();
      this.$refs.saveOrgTree.dropDownVisible = false; // 隐藏模态框
      if (node.length != 0) {
        this.saveForm.parentOrganName = node[0].orgName;
        this.saveOrgTip = node[0].orgName;
      } else {
        this.saveForm.parentOrganName = "";
        this.saveOrgTip = "";
      }
    },
    // 两个密码校验
    checkParentId(rule, value, callback) {
      // 编辑时校验
      if(this.saveFlg!=2){
        callback();
        return}
      systemManage.organCheckParentId({orgId:this.saveForm.orgId,parentId:value}).then(res=>{
         if (res.code==200) {
        callback();
      } else {
        callback(new Error(res.message||"校验不通过"));
      }
      })
     
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    // 查询
    searchFunc() {
      let data = { ...this.searchForm, orgSeq: this.clickNode.orgSeq };
      systemManage.organManageQuery(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
        }
      });
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.saveForm.status = "1";
      this.addOrEdit = true;
       this.$nextTick(()=>{// 清除校验结果
      this.$refs.saveForm.clearValidate();
      })
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      if(!row.parentId){return this.$message.warning('总行不允许修改')}
      let form = { ...row };
      this.saveForm = form;
      this.saveForm.parentOrgId = form.parentId
      this.saveForm.orgLevel = form.orgLevel+'';
      this.oldParentOrgId = form.oldParentOrgId;
      this.addOrEdit = true;
    },
    // 保存
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            parentOrgId: this.saveForm.parentOrgId,
            oldParentOrgId: this.oldParentOrgId,
            organDTO: this.saveForm
          };
          if(data.parentOrgId == data.organDTO.orgId){
            return this.$message.warning('上级机构不能选择自己')
          }
          systemManage
            .organManageUpdate(data)
            .then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.addOrEdit = false;
                this.searchFunc();
                this.getMgrOrganTree();
                this.getOrganTree();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch(err => {});
        }
      });
    },
    startOrBackFunc(num) {
      let selection = this.$refs.multipleTable.selection;
      let str = num == 1 ? "启用" : "停用";
      if (selection.length < 1) {
        return this.$message.warning(`请选择要${str}的机构`);
      }
      this.$confirm(`确定要${str}所选机构吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            ids: this.$refs.multipleTable.selection.map(v => v.orgId)
          };
          if (num == 1) {
            // 调启用接口
            systemManage.organManageStart(data).then(res => {
              if (res.code == 200){
                 this.$message.success(str + "成功");
                 this.searchFunc();
              }else{
                 this.$message.error(res.message);
              }
            });
          } else {
            // 调停用接口
            systemManage.organManageStop(data).then(res => {
              if (res.code == 200){
                 this.$message.success(str + "成功");
                 this.searchFunc();
              }else{
                 this.$message.error(res.message);
              }
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + str
          });
        });
    },
    // 处理部门类型联动
    orgDeptFlagChange(val){
      if(val!=1){
        this.saveForm.orgType = ""
      }
      this.$refs.saveForm.validateField('orgType')
    },
    handleNodeClick(obj) {
      // 单选处理
      let node = { ...obj };
      this.clickNode = node;
      this.searchFunc();
    },
    rendertree(h, { node, data, store }) {
      return <span title={data.orgName}>{data.orgName}</span>;
    },
    authorizeFor(row) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row,true);
    },
    saveConfigTree() {},
    saveConfigTable() {},
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc()
    }
  
  }
};
</script>

<style lang="scss" scoped>
.top-title {
  
font-size: 14px;
font-family: PingFangSC-Medium, PingFang SC;
font-weight: 500;
color: #000000;
line-height: 20px;
vertical-align: middle;
margin-top: 9px;
}
.vertical-bar {
  line-height: 20px;
  font-weight: 500px;
}
</style>